'use strict'

window.onload = init;
var context;    // Audio context
var buf;        // Audio buffer

function init() {
    if (!window.AudioContext) {
        if (!window.webkitAudioContext) {
            //console.log("Your browser does not support any AudioContext and cannot play back this audio.");
            return;
        }
        window.AudioContext = window.webkitAudioContext;
    }

    context = new AudioContext();
}
//
//function playByteArray(bytes) {
//    var buffer = new ArrayBuffer(bytes.length);
//    var view = new Uint8Array(buffer);
//    var len = view.length;
//    for(var i = len; i--;){
//        view[i] = bytes[i].charCodeAt(0);
//    }
//    buffer.set(new Int8Array(bytes), 0);
//
//    context.decodeAudioData(buffer.buffer, play);
//}
//
//function play(audioBuffer) {
//    var source = context.createBufferSource();
//    source.buffer = audioBuffer;
//    source.connect( context.destination );
//    source.start(0);
//}

function playByteArray(byteArray) {

    var arrayBuffer = new ArrayBuffer(byteArray.length);
    var bufferView = new Int8Array(arrayBuffer);
    for (var i = 0; i < byteArray.length; i++) {
        bufferView[i] = byteArray[i];
    }

    context.decodeAudioData(arrayBuffer, function(buffer) {
        buf = buffer;
        play();
    });
}

// Play the loaded file
function play() {
    // Create a source node from the buffer
    var source = context.createBufferSource();
    source.buffer = buf;
    // Connect to the final output node (the speakers)
    source.connect(context.destination);
    // Play immediately
    source.start(0);
}